package com.tedu.egweibo1.controller;

import com.tedu.egweibo1.mapper.UserMapper;
import com.tedu.egweibo1.pojo.dto.UserLoginDTO;
import com.tedu.egweibo1.pojo.dto.UserRegDTO;
import com.tedu.egweibo1.pojo.entity.User;
import com.tedu.egweibo1.pojo.vo.UserVO;
import com.tedu.egweibo1.result.JsonResult;
import com.tedu.egweibo1.result.StatusCode;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpSession;
import java.util.Date;

@Api(tags = "用户模块")
@Slf4j
@RestController
@RequestMapping("/v1/users")
public class UserController {
    @Autowired
    private UserMapper userMapper;


    @ApiOperation(value = "用户注册")
    @PostMapping("/reg")
    public JsonResult regUser(@RequestBody @Validated UserRegDTO userRegDTO){
//        if (userRegDTO.getUsername()==null ||userRegDTO.getUsername().isEmpty()){
//            throw  new IllegalArgumentException("注册名字不能为空");
//        }
        User findUser=userMapper.selectUserByUsername(userRegDTO.getUsername());
        if(findUser!=null){
            return new JsonResult(StatusCode.USERNAME_EXISTS);
        }
        User user=new User();
        BeanUtils.copyProperties(userRegDTO,user);
        user.setCreated(new Date());
        userMapper.insertUser(user);
        return new JsonResult(StatusCode.OPERATION_SUCCESS);

    }

    @ApiOperation("用户登录功能")
    @PostMapping("/login")
    public JsonResult loginUser(@RequestBody UserLoginDTO userLoginDTO, @ApiIgnore HttpSession session){
        User findUser=userMapper.selectUserByUsername(userLoginDTO.getUsername());
        if (findUser!=null){
            if (findUser.getPassword().equals(userLoginDTO.getPassword())){
                session.setAttribute("user",findUser);
                return new JsonResult(StatusCode.OPERATION_SUCCESS);
            }else {
                return new JsonResult(StatusCode.PASSWORD_ERROR);
            }

        }
        return new JsonResult(StatusCode.USERNAME_ERROR);

    }

    @ApiOperation("获取当前用户功能")
    @GetMapping("/currentUser")
    public JsonResult getCurrentUser(@ApiIgnore HttpSession session){
        User user=(User)session.getAttribute("user");
        if(user!=null){
            UserVO userVO=new UserVO();
            BeanUtils.copyProperties(user,userVO);
            return JsonResult.success(userVO);
        }
        return JsonResult.success();
    }
    @ApiOperation("退出登录功能")
    @GetMapping("/logout")
    public JsonResult logout(@ApiIgnore HttpSession session){
        session.removeAttribute("user");
        return  JsonResult.success();
    }





}
